package com.atguigu.gulimall.ware.config;

import com.rabbitmq.client.impl.recovery.QueueRecoveryListener;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author ShiJieLin
 * @Date 2022/5/1 20:29
 * @Version 1.0
 */
@Configuration
public class RabbitMqConfig {

    /** 库存服务的交换机
     */
    public static final String STOCK_EVENT_EXCHANGE = "stock.event.exchange";
    /** 普通队列
     */
    public static final String STOCK_RELEASE_QUEUE = "stock.release.queue";
    /** 延迟队列
     */
    public static final String STOCK_DELAY_QUEUE = "stock.delay.queue";

    /** RabbitMQ发送接收消息的格式
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /** 创建库存服务的交换机
     * @return
     */
    @Bean
    public Exchange stockEventExchange(){

        return ExchangeBuilder.topicExchange(STOCK_EVENT_EXCHANGE)
                .durable(true).build();
    }

    /** 创建普通队列
     * @return
     */
    @Bean
    public Queue stockReleaseQueue(){
        return QueueBuilder.durable(STOCK_RELEASE_QUEUE).build();
    }

    /** 普通队列与交换机的绑定
     * @return
     */
    @Bean
    public Binding stockBinding(Queue stockReleaseQueue, Exchange stockEventExchange){
        return BindingBuilder.bind(stockReleaseQueue)
                .to(stockEventExchange).with("stock.release.#").noargs();
    }

    /** 创建延时队列
     * @return
     */
    @Bean
    public Queue stockDelayQueue(){
        Map<String, Object> arguments = new HashMap<>(3);
        // 指定死信交换机
        arguments.put("x-dead-letter-exchange", STOCK_EVENT_EXCHANGE);
        // 指定死信交换机消费的路由键
        arguments.put("x-dead-letter-routing-key", "stock.release");
        // 消息过期时间 2分钟
        arguments.put("x-message-ttl", 120000);
        return QueueBuilder.durable(STOCK_DELAY_QUEUE).withArguments(arguments).build();
    }
    /** 普通队列与交换机的绑定
     * @return
     */
    @Bean
    public Binding stockDelayBinding(Queue stockDelayQueue, Exchange stockEventExchange){

        return BindingBuilder.bind(stockDelayQueue)
                .to(stockEventExchange).with("stock.locked").noargs();
    }


}
